#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoop.h"
#include "include/muduo/net/TcpConnection.h"

#include <iostream>
#include <functional>
#include <unordered_map>
class TranslateServer
{
public:
    TranslateServer(uint16_t port)
    : _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port),
    "Translate", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::onConnect, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::onMessage, this, std::placeholders::_1, 
        std::placeholders::_2, std::placeholders::_3));
    }
    void Start()
    {
        _server.start();
        _baseloop.loop();
    }
private:
    void onConnect(const muduo::net::TcpConnectionPtr& conn)
    {
        if (conn->connected())
        {
            std::cout << "新连接建立成功！" << std::endl;
        }
        else
        {
            std::cout << "新连接关闭" << std::endl;
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp time)
    {
        std::string str = buf->retrieveAllAsString();
        std::string resp = Translate(str);
        conn->send(resp);
    }
    std::string Translate(const std::string& str)
    {
        static std::unordered_map<std::string, std::string> dict = {
            {"hello", "你好"},
            {"你好", "hello"}
        };
        auto it = dict.find(str);
        if (it == dict.end()) return "None!";
        return it->second;
    }
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    TranslateServer server(8888);
    server.Start();

    return 0;
}